<template>
  <div class="markdown-renderer" v-html="renderedContent"></div>
</template>

<script lang="ts" setup>
import { computed, onMounted, withDefaults, watch, nextTick } from 'vue';
import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';

interface Props {
  content?: string | null;
}

const props = withDefaults(defineProps<Props>(), {
  content: ''
});

// 配置highlight.js
hljs.configure({
  ignoreUnescapedHTML: true
});

// 配置marked选项
marked.setOptions({
  breaks: false,
  gfm: true,
});

const renderedContent = computed(() => {
  const content = props.content;
  if (!content || typeof content !== 'string') {
    return '';
  }
  try {
    return marked.parse(content);
  } catch (error) {
    console.error('Markdown rendering error:', error);
    return '<p>Error rendering markdown content</p>';
  }
});

onMounted(() => {
  // 等待DOM渲染后初始化
  setTimeout(() => {
    initializeCodeBlocks();
  }, 100);
});

// 初始化代码块的所有功能
const initializeCodeBlocks = () => {
  const codeBlocks = document.querySelectorAll('.markdown-renderer pre');
  
  codeBlocks.forEach((pre, index) => {
    const codeElement = pre.querySelector('code');
    if (!codeElement) return;
    
    // 1. 处理语言检测和高亮
    const className = codeElement.className;
    let language = '';
    
    // 提取语言信息
    if (className) {
      const match = className.match(/language-(\w+)/);
      if (match) {
        language = match[1];
      }
    }
    
    // 特殊处理 shell 相关语言
    if (language === 'shell' || language === 'sh' || language === 'zsh' || language === 'fish') {
      language = 'bash'; // highlight.js 使用 'bash' 作为 shell 的标识符
    }
    
    // 其他常见的语言别名映射
    const languageMap: { [key: string]: string } = {
      'js': 'javascript',
      'ts': 'typescript',
      'py': 'python',
      'rb': 'ruby',
      'md': 'markdown',
      'yml': 'yaml'
    };
    
    if (languageMap[language]) {
      language = languageMap[language];
    }
    
    // 手动设置语言并高亮
    if (language && hljs.getLanguage(language)) {
      try {
        const result = hljs.highlight(codeElement.textContent || '', { language: language });
        codeElement.innerHTML = result.value;
        codeElement.className = `hljs language-${language}`;
      } catch (err) {
        console.warn(`代码高亮失败 (${language}):`, err);
        hljs.highlightElement(codeElement);
      }
    } else {
      // 使用自动检测
      hljs.highlightElement(codeElement);
    }
    
    // 2. 添加行号
    addLineNumbers(pre as HTMLElement, codeElement as HTMLElement);
    
    // 3. 添加复制按钮
    addCopyButton(pre as HTMLElement);
    
    // 4. 添加macOS风格交通灯
    addTrafficLights(pre as HTMLElement);
    
    // 5. 添加展开/折叠功能
    addExpandCollapse(pre as HTMLElement, index);
  });
};

// 添加行号
const addLineNumbers = (pre: HTMLElement, code: HTMLElement) => {
  // 检查是否已添加行号
  if (pre.querySelector('.line-numbers')) return;
  
  const lines = code.textContent?.split('\n') || [];
  const lineNumbers = document.createElement('div');
  lineNumbers.className = 'line-numbers';

  for (let i = 1; i <= lines.length; i++) {
    const span = document.createElement('span');
    span.textContent = i.toString();
    lineNumbers.appendChild(span);
  }

  pre.appendChild(lineNumbers);
};

// 添加复制按钮
const addCopyButton = (pre: HTMLElement) => {
  // 检查是否已经添加过复制按钮
  if (pre.querySelector('.code-header')) return;

  // 创建复制按钮容器
  const buttonWrapper = document.createElement('div');
  buttonWrapper.className = 'code-header';

  // 创建复制按钮
  const copyButton = document.createElement('button');
  copyButton.className = 'copy-button';
  copyButton.innerHTML = '📋 复制';
  copyButton.title = '复制代码';

  // 添加点击事件
  copyButton.addEventListener('click', async () => {
    try {
      const code = pre.querySelector('code');
      if (!code) return;
      
      await navigator.clipboard.writeText(code.textContent || '');
      copyButton.innerHTML = '✅ 已复制';
      copyButton.classList.add('copied');
      setTimeout(() => {
        copyButton.innerHTML = '📋 复制';
        copyButton.classList.remove('copied');
      }, 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  });

  // 将按钮添加到代码块
  buttonWrapper.appendChild(copyButton);
  pre.appendChild(buttonWrapper);
};

// 添加macOS风格交通灯
const addTrafficLights = (pre: HTMLElement) => {
  // 使用CSS的::before伪元素来添加交通灯，不需要额外的DOM元素
  pre.classList.add('has-traffic-lights');
};

// 添加展开/折叠功能
const addExpandCollapse = (pre: HTMLElement, index: number) => {
  // 移除可能存在的旧按钮
  const oldButton = pre.querySelector('.expand-button');
  if (oldButton) {
    oldButton.remove();
  }

  // 获取代码块的实际高度
  const actualHeight = pre.scrollHeight;
  
  if (actualHeight > 500) {
    // 添加折叠类
    pre.classList.add('collapsed');
    
    // 创建展开按钮
    const expandButton = document.createElement('button');
    expandButton.className = 'expand-button';
    expandButton.innerHTML = '⬇️ 展开代码';
    
    // 添加点击事件
    expandButton.onclick = (e) => {
      e.stopPropagation();
      const isCollapsed = pre.classList.contains('collapsed');
      if (isCollapsed) {
        pre.classList.remove('collapsed');
        expandButton.innerHTML = '⬆️ 收起代码';
      } else {
        pre.classList.add('collapsed');
        expandButton.innerHTML = '⬇️ 展开代码';
      }
    };
    
    pre.appendChild(expandButton);
  }
};

// 监听内容变化，重新初始化代码块
watch(() => props.content, () => {
  nextTick(() => {
    setTimeout(() => {
      initializeCodeBlocks();
    }, 100);
  });
});
</script>

<style scoped>
@font-face {
  font-family: 'MarkdownFont';
  src: url('@/assets/iconfont/2.woff2') format('woff2');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

.markdown-renderer {
  line-height: 1.8;
  color: var(--text-primary);
  font-size: 1.1em;
  font-family: 'MarkdownFont', 'CustomFont', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', -apple-system, BlinkMacSystemFont, sans-serif !important;
}

/* 重置缩进 */
.markdown-renderer :deep(*) {
  text-indent: 0 !important;
}

/* 确保所有文本元素使用全局字体 */
.markdown-renderer :deep(h1),
.markdown-renderer :deep(h2),
.markdown-renderer :deep(h3),
.markdown-renderer :deep(h4),
.markdown-renderer :deep(h5),
.markdown-renderer :deep(h6),
.markdown-renderer :deep(p),
.markdown-renderer :deep(li),
.markdown-renderer :deep(blockquote),
.markdown-renderer :deep(td),
.markdown-renderer :deep(th),
.markdown-renderer :deep(span),
.markdown-renderer :deep(div),
.markdown-renderer :deep(strong),
.markdown-renderer :deep(em) {
  font-family: 'MarkdownFont', 'CustomFont', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', -apple-system, BlinkMacSystemFont, sans-serif !important;
}

/* 标题样式 */
.markdown-renderer :deep(h2) {
  font-size: 1.8em;
  margin: 2rem 0 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 2px solid rgba(102, 126, 234, 0.1);
  position: relative;
  color: var(--text-primary);
}

.markdown-renderer :deep(h2)::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 50px;
  height: 2px;
  background: #667eea;
}

.markdown-renderer :deep(h3) {
  font-size: 1.4em;
  margin: 1.5rem 0 1rem;
  color: var(--text-primary);
  position: relative;
  padding-left: 1rem;
}

.markdown-renderer :deep(h3)::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: #667eea;
  border-radius: 2px;
}

/* 段落样式 */
.markdown-renderer :deep(p) {
  margin: 1rem 0;
  color: var(--text-secondary);
  line-height: 1.8;
}

/* 链接样式 */
.markdown-renderer :deep(a) {
  color: #667eea;
  text-decoration: none;
  border-bottom: 1px dashed #667eea;
  transition: all 0.3s ease;
}

.markdown-renderer :deep(a:hover) {
  color: var(--primary-dark);
  border-bottom-style: solid;
}

/* 引用样式 */
.markdown-renderer :deep(blockquote) {
  margin: 1.5rem 0;
  padding: 1rem 1.5rem;
  background: var(--hover-bg);
  border-left: 4px solid #667eea;
  border-radius: 4px;
  color: var(--text-secondary);
  font-style: italic;
}

.markdown-renderer :deep(blockquote p) {
  margin: 0;
}

/* 列表样式 */
.markdown-renderer :deep(ul),
.markdown-renderer :deep(ol) {
  margin: 1rem 0;
  padding-left: 2rem;
  color: var(--text-secondary);
}

.markdown-renderer :deep(li) {
  margin-bottom: 0.5rem;
  position: relative;
}

.markdown-renderer :deep(li)::marker {
  color: #667eea;
}

/* 行内代码样式 */
.markdown-renderer :deep(code:not([class])) {
  font-size: 14px;
  line-height: 1.5;
  position: relative;
  color: rgb(239, 89, 84);
  background: rgb(243, 244, 244);
  border-radius: 6px;
  padding: 2px 6px;
  margin: 0 2px;
}

/* 代码块样式 */
.markdown-renderer :deep(pre) {
  margin: 1em 0;
  position: relative;
  background: #282c34;
  border-radius: 6px;
  padding-top: 2.5em;
  overflow: hidden;
  max-height: 2000px;
  transition: max-height 0.4s ease-in-out;
}

.markdown-renderer :deep(pre.collapsed) {
  max-height: 300px;
}

.markdown-renderer :deep(pre.collapsed)::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: linear-gradient(transparent, #282c34);
  pointer-events: none;
  z-index: 2;
}

.markdown-renderer :deep(pre.collapsed .expand-button) {
  display: flex !important;
}

/* 展开按钮样式 */
.markdown-renderer :deep(.expand-button) {
  position: absolute;
  bottom: 15px;
  left: 50%;
  transform: translateX(-50%);
  padding: 6px 16px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  color: #abb2bf;
  cursor: pointer;
  z-index: 3;
  font-size: 0.9em;
  align-items: center;
  gap: 6px;
  transition: all 0.2s ease;
  white-space: nowrap;
  display: none;
}

.markdown-renderer :deep(.expand-button:hover) {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  transform: translateX(-50%) translateY(-2px);
}


/* 行号容器样式 */
.markdown-renderer :deep(.line-numbers) {
  position: absolute;
  left: 0;
  top: 2.5em;
  bottom: 0;
  font-size: 14px;
  padding: 1em 0;
  text-align: right;
  color: #666;
  border-right: 1px solid #404040;
  background: #2d323b;
  user-select: none;
  z-index: 1;
  width: 3.5em;
}

.markdown-renderer :deep(.line-numbers span) {
  display: block;
  padding: 0 0.5em;
  min-width: 2.5em;
  line-height: 1.5;
}

/* 调整代码内容的样式 */
.markdown-renderer :deep(pre code) {
  display: block;
  padding: 1em;
  padding-left: 4em;
  margin-left: 0;
  overflow-x: auto;
  font-family: 'Fira Code', monospace;
  font-size: 14px;
  line-height: 1.5;
  position: relative;
  
  /* 重要：不要覆盖 highlight.js 的颜色样式 */
  color: inherit;
  background: inherit;
}

/* 确保 highlight.js 的样式能够正常显示 */
.markdown-renderer :deep(.hljs) {
  background: #282c34 !important;
  color: #abb2bf !important;
}

.markdown-renderer :deep(.hljs-comment),
.markdown-renderer :deep(.hljs-quote) {
  color: #5c6370 !important;
}

.markdown-renderer :deep(.hljs-keyword),
.markdown-renderer :deep(.hljs-selector-tag),
.markdown-renderer :deep(.hljs-literal),
.markdown-renderer :deep(.hljs-type) {
  color: #c678dd !important;
}

.markdown-renderer :deep(.hljs-string),
.markdown-renderer :deep(.hljs-regexp) {
  color: #98c379 !important;
}

.markdown-renderer :deep(.hljs-number) {
  color: #d19a66 !important;
}

.markdown-renderer :deep(.hljs-function) {
  color: #61dafb !important;
}

.markdown-renderer :deep(.hljs-variable) {
  color: #e06c75 !important;
}

.markdown-renderer :deep(.hljs-built_in) {
  color: #56b6c2 !important;
}

.markdown-renderer :deep(.hljs-symbol) {
  color: #c678dd !important;
}

/* 添加仿 macOS 风格的交通灯 */
.markdown-renderer :deep(pre.has-traffic-lights)::before {
  content: '';
  position: absolute;
  top: 12px;
  left: 12px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #ff5f56;
  box-shadow:
    20px 0 0 #ffbd2e,
    40px 0 0 #27c93f;
}

/* 复制按钮容器 */
.markdown-renderer :deep(.code-header) {
  position: absolute;
  top: 8px;
  right: 12px;
  z-index: 2;
  opacity: 0;
  transition: opacity 0.2s ease;
}

/* 显示复制按钮 */
.markdown-renderer :deep(pre:hover .code-header) {
  opacity: 1;
}

/* 复制按钮样式 */
.markdown-renderer :deep(.copy-button) {
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 4px;
  color: #abb2bf;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}


.markdown-renderer :deep(.copy-button:hover) {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.markdown-renderer :deep(.copy-button.copied) {
  background: #98c379;
  color: #fff;
}

/* 图片样式 */
.markdown-renderer :deep(img) {
  max-width: 100%;
  border-radius: 8px;
  margin: 1.5rem 0;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  cursor: zoom-in;
}

.markdown-renderer :deep(img:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 表格样式 */
.markdown-renderer :deep(table) {
  width: 100%;
  margin: 1.5rem 0;
  border-collapse: collapse;
  border-radius: 8px;
  overflow: hidden;
}

.markdown-renderer :deep(table th),
.markdown-renderer :deep(table td) {
  padding: 0.75rem 1rem;
  border: 1px solid var(--border-color);
}

.markdown-renderer :deep(table th) {
  background: var(--hover-bg);
  color: var(--text-primary);
  font-weight: 500;
  text-align: left;
}

.markdown-renderer :deep(table tr:nth-child(even)) {
  background: var(--hover-bg);
}

/* 分割线样式 */
.markdown-renderer :deep(hr) {
  margin: 2rem 0;
  border: none;
  height: 1px;
  background: var(--border-color);
  position: relative;
}

.markdown-renderer :deep(hr)::before {
  content: '§';
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: var(--card-bg);
  padding: 0 1rem;
  color: var(--text-secondary);
  font-size: 1.2em;
}
</style>